package io.chance.receiverlei.schedule;

import io.chance.receiverlei.db.DbManager;
import io.chance.receiverlei.db.model.MonitorDataHourModel;
import lrq.common.MyLog;
import lrq.data.DataTable;
import lrq.data.ParameterCollection;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class StatisticsHourData implements Job {
	
	Logger log = MyLog.getLogger(getClass().getSimpleName());

	@Override  
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		
		try {
			log.info("开始统计小时数据");
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.MINUTE,0);
			cal.set(Calendar.SECOND,0);
			
			Date startDate = cal.getTime();
			cal.add(Calendar.HOUR_OF_DAY, -1);
			Date endDate = cal.getTime();
			
//			String sql = " select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') QN,'N' FLAG,sys_guid() guid,? datatime,SITE_ID,avg(rtd) avg,max(rtd) max,min(rtd) min,DEVICETYPE from monitor_data where datatime > ? and datatime < ? "
//					+ " group by mn,DEVICETYPE ";
			String sql = " select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') QN,'N' FLAG,sys_guid() id,? datatime,SITE_ID,avg(rtd) avg,max(rtd) max,min(rtd) min,poll_code from D_BC_SITE where datatime " +
				">" +
				" ? and datatime < ? "
					+ " group by mn,poll_code ";
			ParameterCollection pc = new ParameterCollection();
			pc.add(startDate);
			pc.add(endDate);
			pc.add(startDate);
			
			DataTable table = DbManager.getDbExecuter().executeQuery(sql, pc);
			List<MonitorDataHourModel> models = table.toModels(MonitorDataHourModel.class);

			if(models!=null && models.size()>0){
				DbManager.getDbExecuter().Create(models);
				log.info("小时数据插入成功："+models.size());
			}
		} catch (Exception e) {
			log.error("统计小时数据出错", e);
		}
	}
}
